<template>
  <div class="app-container">
    <section class="template">
        <div ref="imageDom" id="pdfDom" class="bg" crossOrigin='anonymous' >
          <div class="logo" v-drag><img style="width:100px;height:auto" draggable="false" src="@/assets/images/jbllogo.png"/></div>
          <span class="name" v-drag>· {{ruleForm.name}} ·</span>
          <span class="remark" v-drag>{{ruleForm.remark}}</span>
          <span  class="title" v-drag>{{ruleForm.title}}</span>
          <span class="title2" v-drag>{{ruleForm.title2}}</span>
          <span class="choose" v-drag>{{ruleForm.courseName}}</span>
          <div class="edit" v-drag>
            <span>{{ruleForm.edit}}</span>
          </div>
          <div class="qrcode" v-drag>
            <img :src="qrcode" draggable="false" alt="">
          </div>
          <div class="phone" v-drag>
            <span>{{ruleForm.phone}}</span>
            <span>{{ruleForm.peop}}</span>
          </div>
          <div class="address" v-drag>
            <div class="info">{{ruleForm.address}}</div>
          </div>
          <div class="course-img" v-drag>
            <img crossOrigin="Anonymous" referrerPolicy='origin' draggable="false" :src="courseImg" v-drag>
          </div>
          <img id="bg-img-box" class="bg-img" draggable="false" crossOrigin='anonymous' src="https://ossdev0.jiabala.com/kJakQtZrOveyM" alt="">
        </div>
      <div class="form">
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="活动名称" prop="name">
            <el-input v-model="ruleForm.name" placeholder="请输入活动名称"></el-input>
          </el-form-item>
          <el-form-item label="活动简介">
            <el-input v-model="ruleForm.remark" placeholder="请输入活动简介"></el-input>
          </el-form-item>
          <el-form-item label="标题一" prop="title">
            <el-input v-model="ruleForm.title" placeholder="请输入标题一"></el-input>
          </el-form-item>
          <el-form-item label="选择课程" prop="choose">
            <el-select
             v-model="ruleForm.choose"
             placeholder="请选择"
             no-data-text="无上架课程"
             @change="changeChoose">
              <el-option
                v-for="item in courseOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="标题二" prop="title2">
            <el-input v-model="ruleForm.title2" placeholder="请输入标题二"></el-input>
          </el-form-item>
          <el-form-item label="内容编辑区" prop="edit">
            <el-input
              v-model="ruleForm.edit"
              type="textarea"
              :autosize="{ minRows: 4, maxRows: 8}"
              placeholder="优势"
            ></el-input>
          </el-form-item>
          <el-form-item label="咨询热线" prop="phone">
            <el-input v-model="ruleForm.phone" placeholder="请输入联系电话"></el-input>
          </el-form-item>
          <el-form-item label="联系人">
            <el-input v-model="ruleForm.peop" placeholder="请输入联系老师"></el-input>
          </el-form-item>
          <el-form-item label="地址" prop="address">
            <el-input v-model="ruleForm.address" placeholder="默认为机构预留的地址"></el-input>
          </el-form-item>
          <!-- <el-form-item label="备注" prop="detail">
            <el-input v-model="ruleForm.detail" placeholder="请输入备注"></el-input>
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" :loading="submitLoading" @click="preview('ruleForm')">预览</el-button>
            <!-- <el-button type="primary"  @click="getPdf()">预览</el-button> -->
            <!-- <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button> -->
          </el-form-item>
        </el-form>
      </div>
    </section>
    <el-dialog
      title="预览海报"
      :visible.sync="dialogVisible"
      width='550px'
      >
      <!-- <div class="privew-info">如生成海报图片不完整，点击 <i class="el-icon-refresh icon-ref" @click="refreshPrivew"></i> 试试</div> -->
      <div class="canvas-box">
        <div class="canvas-img">
          <img :src="imgUrl">
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleDownload">
          <!-- <a download="downImg" :href="imgUrl"> -->
            下 载
          <!-- </a> -->
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Cookies from 'js-cookie'
import html2canvas from 'html2canvas'
import { randomString } from '@/utils'
// import { getCourseByBusId } from '@/api/marketing'
import { courseList, QRcode } from '@/api/curriculum'
export default {
  name: 'TemplateEdit3',
  data() {
    return {
      submitLoading: false,
      scrollXwidth: null,
      scrollYheight: null,
      dialogVisible: false,
      courseImg: 'https://ossdev0.jiabala.com/8eFKWPDCMw.png', // 课程图片
      qrcode: '', // 二维码图片
      imgUrl: '',
      widthVal: '926', // 存放要缩放元素.app-shrink的实时变动宽度值
      oldWidthVal: '926', // 存放.app-shrink-drag是触发鼠标按下时，要缩放元素.app-shrink的su宽度值。
      dragVal: 0, // 存放实时鼠标的x轴移动值
      bg: 'https://ossdev0.jiabala.com/kJakQtZrOveyM',
      ruleForm: {
        courseName: '芭蕾舞(测试)',
        name: '体悟艺术之态 培养人文修养',
        remark: '百川国画培训中心',
        title: '活动课程',
        choose: '',
        title2: '机构介绍',
        edit:
          '卡乐图国际儿童艺术中心：以多年的教育经验结合孩子的发展趋势，有专业的教学团队制定出智能构建课程，在将教学核心应用到实际课堂的过程中得到家长的高度认可。',
        phone: '18924683325',
        peop: ' 房老师',
        address: '广东省佛山市顺德区大良街道汇峰商厦五座202',
        detail: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入活动名称', trigger: 'change' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        remark: [
          { required: true, message: '请输入活动简介', trigger: 'change' }
        ],
        title: [
          { required: true, message: '请输入标题', trigger: 'change' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        title2: [
          { required: true, message: '请输入标题', trigger: 'change' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        choose: [{ required: true, message: '请选择课程', trigger: 'blur' }],
        edit: [{ required: true, message: '请输入内容', trigger: 'blur' }],
        phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
        address: [{ required: true, message: '请输入地址', trigger: 'blur' }]
      },
      courseOptions: [],
      nameStyle: {
        position: 'absolute',
        top: '20px',
        left: '20px',
        'font-size': '26px',
        color: '#fff',
        'font-weight': 600
      }
    }
  },
  // 注册局部组件指令
  directives: {
    drag: function(el) {
      const dragBox = el // 获取当前元素
      dragBox.onmousedown = e => {
        // 算出鼠标相对元素的位置
        const disX = e.clientX - dragBox.offsetLeft
        const disY = e.clientY - dragBox.offsetTop
        document.onmousemove = e => {
          // 用鼠标的位置减去鼠标相对元素的位置，得到元素的位置
          const left = e.clientX - disX
          const top = e.clientY - disY
          // 移动当前元素
          dragBox.style.left = left + 'px'
          dragBox.style.top = top + 'px'
        }
        document.onmouseup = e => {
          // 鼠标弹起来的时候不再移动
          document.onmousemove = null
          // 预防鼠标弹起来后还会循环（即预防鼠标放上去的时候还会移动）
          document.onmouseup = null
        }
      }
    }
  },
  computed: {},
  watch: {
    ruleForm: {
      handler(newName, oldName) {
      },
      immediate: true
    }
  },
  created() {
    courseList({
      'businessId': this.$store.getters.businessId,
      'currentPage': 1,
      'pageSize': 99,
      'status': 3
    }).then(res => {
      this.courseOptions = res.data.records
      // this.courseImg = res.data.records.length > 0 ? res.data.records[0].introducePictures : ''
      // this.ruleForm.choose = res.data.records.length > 0 ? res.data.records[0].id : null
      // this.ruleForm.courseName = res.data.records.length > 0 ? res.data.records[0].name : ''
      res.data.records.length > 0 && QRcode({
        id: res.data.records[0].id,
        pagesPath: 'pages/courseDetail/courseDetail'
      }).then(res => {
        const { data } = res
        if (data instanceof Object) {
          this.qrcode = data.qrcodeImg
        } else {
          this.qrcode = data
        }
      })
    })
  },
  mounted() {
    // this.imgToBase64('#bg-img-box', 'https://ossdev0.jiabala.com/kJakQtZrOveyM')
    window.addEventListener('scroll', this.handleScroll, true)
    // window.onresize = () => {
    //  this.fnThrottle(this.reload, 1000, 1000)()
    // }
    //  setTimeout(function () {
    //     this.preview();
    // },1000);
  },
  methods: {
    changeChoose(val) {
      const obj = this.courseOptions.find(i => i.id === val)
      this.ruleForm.courseName = obj.name
      this.courseImg = this.getImgBase64(obj.introducePictures.split(',')[0]) || 'https://ossdev0.jiabala.com/8eFKWPDCMw.png'
      // this.courseImg = obj.introducePictures
      // this.courseImg = this.getBase64ByUrl(obj.introducePictures)
      QRcode({
        id: val,
        pagesPath: 'pages/courseDetail/courseDetail'
      }).then(res => {
        const { data } = res
        if (data instanceof Object) {
          this.qrcode = data.qrcodeImg
        } else {
          this.qrcode = data
        }
      })
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          alert('submit!')
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleScroll() {
      var top = Math.floor(document.body.scrollTop || document.documentElement.scrollTop || window.pageYOffset)
      var left = Math.floor(document.body.scrollLeft || document.documentElement.scrollLeft || window.pageXOffset)
      // console.log(top, left, 'a')
      this.scrollYheight = top
      this.scrollXwidth = left
    },
    // 调用具体转换的方法
    getBase64Images(img) {
      var canvas = document.createElement('canvas')
      canvas.width = img.width
      canvas.height = img.height
      var ctx = canvas.getContext('2d')
      ctx.drawImage(img, 0, 0, img.width, img.height)
      // var ext = img.src.substring(img.src.lastIndexOf('.') + 1).toLowerCase()
      var dataURL = canvas.toDataURL('image/')
      return dataURL
    },
    /* oss图片转base64*/
    getImgBase64(imgurl) {
      const that = this
      var img = new Image()
      img.setAttribute('crossOrigin', 'anonymous')
      // img.src = imgurl + '?v=any_string_is_ok' + Math.random()
      img.src = imgurl + '?v=any_string_is_ok'
      img.onload = function() {
        that.courseImg = that.getBase64Images(img)
      }
    },
    preview(formName) {
      window.scrollTo(0, 0)
      this.submitLoading = false
      const loading = this.$loading({
        lock: true,
        text: '努力生成中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      setTimeout(() => {
        const canvasBox = this.$refs.imageDom
        this.$nextTick(() => {
          // 手动创建一个 canvas 标签
          const canvas = document.createElement('canvas')
          // 获取父标签，意思是这个标签内的 DOM 元素生成图片
          // 获取父级的宽高
          const width = parseInt(window.getComputedStyle(canvasBox).width)
          const height = parseInt(window.getComputedStyle(canvasBox).height)

          // let {width, height} = canvasBox.getBoundingClientRect();
          const dpr = window.devicePixelRatio || 1
          // 宽高 * 2 并放大 2 倍 是为了防止图片模糊
          canvas.width = width * dpr
          canvas.height = height * dpr
          canvas.style.width = width + 'px'
          canvas.style.height = height + 'px'

          const context = canvas.getContext('2d')
          context.scale(dpr, dpr)
          const rectObject = canvasBox.getBoundingClientRect()
          const eleft = rectObject.left
          const etop = rectObject.top
          context.translate(-eleft, -etop)
          // const sidebarStatus = Cookies.get('sidebarStatus') === '0' ? 2 : 5
          html2canvas(this.$refs.imageDom,
            {
              useCORS: true, // 【重要】开启跨域配置
              // allowTaint: true, // 允许跨域图片
              tainttest: true, // 检测每张图片都已经加载完成
              logging: false,
              ...canvas,
              // scrollY: Number(`-${this.scrollYheight || 0}`),
              scrollX: 0,
              proxy: 'https://app.jiabala.com',
              letterRendering: true
              // backgroundColor: null // null 表示设置背景为透明色
            }
          ).then(canvas => {
            let count = [1,2,3,4,5,6,7]
            count.forEach((item,index)=>{
              this.refreshPrivew()
              if(index+1 === count.length){
                 this.dialogVisible = true
                  // 转成图片，生成图片地址
                  this.submitLoading = false
                  loading.close()
                  this.imgUrl = canvas.toDataURL('image/png')                 
              }
            })            
          })
        })
      }, 500)
    },
    refreshPrivew() {
      window.scrollTo(0, 0)
      const loading = this.$loading({
        lock: true,
        text: '努力生成中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      // this.$refs[formName].resetFields()
      const canvasBox = this.$refs.imageDom
      this.$nextTick(() => {
        // 手动创建一个 canvas 标签
        const canvas = document.createElement('canvas')
        // 获取父标签，意思是这个标签内的 DOM 元素生成图片
        // 获取父级的宽高
        const width = parseInt(window.getComputedStyle(canvasBox).width)
        const height = parseInt(window.getComputedStyle(canvasBox).height)

        // let {width, height} = canvasBox.getBoundingClientRect();
        const dpr = window.devicePixelRatio || 1
        // 宽高 * 2 并放大 2 倍 是为了防止图片模糊
        canvas.width = width * dpr
        canvas.height = height * dpr
        canvas.style.width = width + 'px'
        canvas.style.height = height + 'px'

        const context = canvas.getContext('2d')
        context.scale(dpr, dpr)
        const rectObject = canvasBox.getBoundingClientRect()
        const eleft = rectObject.left
        const etop = rectObject.top
        context.translate(-eleft, -etop)
        // const sidebarStatus = Cookies.get('sidebarStatus') === '0' ? 2 : 5
        html2canvas(this.$refs.imageDom,
          {
            useCORS: true, // 【重要】开启跨域配置
            // allowTaint: true, // 允许跨域图片
            tainttest: true, // 检测每张图片都已经加载完成
            logging: false,
            ...canvas,
            // scrollY: Number(`-${this.scrollYheight || 0}`),
            scrollX: 0,
            proxy: 'https://app.jiabala.com',
            letterRendering: true
            // backgroundColor: null // null 表示设置背景为透明色
          }
        ).then(canvas => {
          // 转成图片，生成图片地址
          loading.close()
          this.submitLoading = false
          this.imgUrl = canvas.toDataURL('image/png')
        })
      })
    },
    handleDownload() {
      this.dialogVisible = false
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = this.imgUrl
      link.download = `poster_${randomString(5)}`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },
    // 节流
    fnThrottle(method, delay, duration) {
      var that = this
      var timer = this.timer
      var begin = new Date().getTime()
      return function() {
        var context = that
        var args = arguments
        var current = new Date().getTime()
        clearTimeout(timer)
        if (current - begin >= duration) {
          method.apply(context, args)
          begin = current
        } else {
          // console.log(delay)
          that.timer = setTimeout(function() {
            method.apply(context, args)
          }, delay)
        }
      }
    }
  },
  // 离开当前页面后执行
  destroyed: function() {
    window.removeEventListener('scroll', this.handleScroll)
  }
}
</script>
<style lang='scss' scoped>
.template {
  width: 100%;
  min-width: 1000px;
  display: flex;
  // justify-content: space-around;
  .bg {
    position: relative;
    // top:10px;
    // padding: 20px;
    // position: relative;
    display: flex;
    flex-flow: column;
    align-items: center;
    // width: 4.5rem;
    // height: 8.03rem;
    width: 450px;
    height: 803px;
    min-width: 450px;
    min-height:803px;
    font-family: PingFang SC;
    // background-size: 100% 100%;
    box-sizing: border-box;
    overflow: hidden;
    // border: 1px solid #eee;
    .logo{
      z-index: 2;
      position: absolute;
      left: 46px;
      top: 31px;
    }
    .name {
      z-index: 2;
      cursor: pointer;
      position: absolute;
      top: 82px;
      font-size: 22px;
      font-weight: 600;
      color: #FFD405;
    }
    .remark {
      z-index: 2;
      cursor: pointer;
      position: absolute;
      top: 118px;
      font-size: 46px;
      font-weight: 500;
      color: #fff;
    }
    .title {
      z-index: 2;
      cursor: pointer;
      position: absolute;
      top: 212px;
      left: 64px;
      font-size: 16px;
      font-weight: 600;
      letter-spacing: 6px;
      color: #fff;
      writing-mode: vertical-lr;
    }
    .title2 {
      z-index: 2;
      cursor: pointer;
      position: absolute;
      top: 454px;
      font-size: 20px;
      font-weight: 600;
      color: #fff;
    }
    .choose {
      z-index: 2;
      cursor: pointer;
      position: absolute;
      top: 399px;
      left: 198px;
      font-size: 24px;
      font-weight: 500;
      color: #fff;
    }
    .edit {
      z-index: 2;
      cursor: pointer;
      position: absolute;
      padding: 0 50px;
      display: flex;
      justify-content: center;
      width: 100%;
      top: 495px;
      font-size: 16px;
      font-weight: 500;
      color: #fff;
      line-height: 20px;
      box-sizing: border-box;
      > span {
        text-align: center;
      }
    }
    .phone {
      z-index: 2;
      cursor: pointer;
      position: absolute;
      top: 696px;
      left: 138px;
      font-size: 22px;
      font-weight: 600;
      color: #306BE0;
      box-sizing: border-box;
      >span:nth-of-type(2){
        font-size: 18px;
        font-weight: 500;
      }
    }
    .address {
      z-index: 2;
      cursor: pointer;
      position: absolute;
      display: flex;
      top: 728px;
      left:138px;
      font-size: 14px;
      font-weight: 500;
      color: #000;
      box-sizing: border-box;
    }
    .qrcode{
      z-index: 3;
      position: absolute;
      top: 580px;
      left:310px;
      width:100px;
      height: 100px;
      border: 2px solid #fff;
      box-sizing: content-box;
      border-radius: 50%;
      overflow: hidden;
      >img{
        width:100%;
        height: 100%;
      }
    }
    .course-img {
      z-index: 2;
      cursor: pointer;
      position: absolute;
      top: 203px;
      left: 86px;
      width: 280px;
      height: 170px;
      border: 5px solid #000;
      box-sizing: content-box;
      >img{
        width: 100%;
        height: 100%;
        // object-fit: cover;

      }
    }
  }
  .form {
    z-index: 2;
    margin-left: 100px;
    display: flex;
    align-items: center;
    width: 500px;
    min-height: 803px;
    .demo-ruleForm {
      width: 100%;
    }
  }
}
.bg-img{
  z-index: 1;
  position: absolute;
  top: 0;
  width: 100%;
  height: 100%;
}
.canvas-box{
  z-index: 2;
  display: flex;
  justify-content: center;
  width: 100%;
  .canvas-img{
    display: flex;
    justify-content: center;
    width:450px;
    height: 803px;
    >img{
      width:100%;
      height: 100%;
    }
  }
}
/deep/.el-dialog__body{
  padding: 10px;
}
.privew-info{
  margin-bottom:5px ;
  text-align: center;
  font-size: 14px;
  color:rgb(168, 168, 168);
  .icon-ref{
    cursor: pointer;
    font-size: 16px;
    font-weight: 600;
    color:#1890ff;
    animation: ref 2s ease-in-out 1s infinite normal;
  }
  @keyframes ref
  {
    from {transform: rotate(0deg);}
    to {transform: rotate(360deg);}
  }
}
</style>
